package com.joysuch.wwyt.bp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.joysuch.wwyt.bp.entity.BpRewardJobRule;
import com.joysuch.wwyt.bp.mapper.BpRewardJobRuleMapper;
import com.joysuch.wwyt.bp.service.BpRewardJobRuleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.joysuch.wwyt.core.enums.DeleteFlag;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.mh.entity.ScreenMapConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author heqifeng
 * @since 2022-01-06
 */
@Service
public class BpRewardJobRuleServiceImpl extends ServiceImpl<BpRewardJobRuleMapper, BpRewardJobRule> implements BpRewardJobRuleService {
    @Autowired
    private BpRewardJobRuleMapper mapper;


    @Override
    public void saveOrUpdateBatchByJobId(List<BpRewardJobRule> jobRuleMapping) {
        ArrayList<Long> allUseJobs = new ArrayList<>();
        jobRuleMapping.forEach(each -> {
            allUseJobs.add(each.getJobId());
            if (hasRuleForJob(each.getJobId())) {
                mapper.updateByJobId(each);
            }else {
                save(each);
            }
        });
        if (allUseJobs.size() > 0) {
            // 删除本次保存未使用的规则(not in)
            deleteUselessRule(allUseJobs);
        }
    }

    @Override
    public List<BpRewardJobRule> getByRuleId(Long ruleId) {
        LambdaQueryWrapper<BpRewardJobRule> wrapper = new LambdaQueryWrapper<BpRewardJobRule>();
        wrapper.eq(BpRewardJobRule::getDeleteFlag, DeleteFlag.EFFECTIVE.getCode());
        wrapper.eq(BpRewardJobRule::getOrgCode, Context.getCurrentOrgCode());
        wrapper.eq(BpRewardJobRule::getTenentId, Context.getCurrentTenantId());
        wrapper.eq(BpRewardJobRule::getRuleId,ruleId);
        return mapper.selectList(wrapper);
    }

    public boolean hasRuleForJob(Long jobId) {
        LambdaQueryWrapper<BpRewardJobRule> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BpRewardJobRule::getDeleteFlag, DeleteFlag.EFFECTIVE.getCode());
        wrapper.eq(BpRewardJobRule::getOrgCode, Context.getCurrentOrgCode());
        wrapper.eq(BpRewardJobRule::getTenentId, Context.getCurrentTenantId());
        wrapper.eq(BpRewardJobRule::getJobId,jobId);
        return mapper.selectCount(wrapper) > 0;
    }

    public void deleteUselessRule(List<Long> useJobs) {
        mapper.deleteByJobIdNotIn(useJobs);
    }
}
